package utils

import (
	"database/sql"
	"fmt"
	_ "github.com/astaxie/beego"
	_ "github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

/**
 ** @author: hui
 ** @email: 3231954428@qq.com
 ** @phone: 15779563913
 ** @DataTime: 2021/12/15 16:47
 **/


const (
	USERNAME = "root"
	PASSWORD = "root"
	HOST = "127.0.0.1"
	PORT = "3306"
	DATABASE_NAME = "finaltest"
	DRIVER_NAME = "mysql"
)

var db *sql.DB

func ConnectDB() {
	//conf := beego.AppConfig

	//userName, _ := conf.String("username")
	//pwd, _ := conf.String("password")
	//host, _ := conf.String("host")
	//port, _ := conf.String("port")
	//databaseName, _ := conf.String("databasename")
	//driverName, _ := conf.String("drivername")
	dbConnStr := USERNAME + ":" + PASSWORD + "@tcp(" + HOST + ":" + PORT + ")/" + DATABASE_NAME + "?charset=utf8"
	//dbConnStr := userName + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + databaseName + "?charset=utf8"

	//orm.RegisterDriver(DRIVER_NAME, orm.DRMySQL)

	//连接数据库
	dbObject, err := sql.Open(DRIVER_NAME, dbConnStr)
	if err != nil{
		fmt.Println("连接数据库错误：", err)
		return
	}
	db = dbObject
	fmt.Println("连接数据库成功")

}
// 根据指定的条件查询数据,返回查询到的单条记录
func Query(sql string, args ...interface{}) *sql.Row  {
	row := db.QueryRow(sql, args...)
	return row
}

// 实现对表数据的插入, 修改, 删除的操作
func ExecDB(sql string, args ...interface{}) (count, id int64, err error) {
	result, err := db.Exec(sql, args...)
	if err != nil {
		fmt.Println("执行指定的SQL语句时发生错误. sql: ", sql)
		return 0, 0, err
	}

	count, err = result.RowsAffected()	// RowsAffected(): 返回本次操作所影响的行数
	if err != nil {
		fmt.Println("查询影响的行数时发生错误 ")
		return 0, 0, err
	}

	id, err = result.LastInsertId()	// LastInsertId(): 返回本次操作(必须为插入数据)所自动生成的主键ID值
	if err != nil {
		fmt.Println("获取返回的主键ID值时发生错误 ")
		return count, 0, err
	}
	return count, id, nil
}